<template>
  <div>
    <ul>
      <tree-node
        v-for="node in treeData"
        :key="node.id"
        :node="node"
        @toggle="handleToggle"
        @check="handleCheck"
      />
    </ul>
  </div>
</template>

<script lang="ts" setup>
import { ref,defineEmits  } from 'vue';
import TreeNode from './TreeNode.vue';
import {treeStruct} from "../script/data"

// 其他组件传入内容
const AddGraphicLayer = 'add-graphic-layer';
const RemoveGraphicLayer = 'remove-graphic-layer';

const emit = defineEmits([AddGraphicLayer,RemoveGraphicLayer]);

interface TreeNode {
  id: number;
  label: string;
  children?: TreeNode[];
  checked?: boolean;
  expanded?: boolean;
  indeterminate?: boolean;
}


// NOTE:构建目录树结构
let count = 0;
let treeContent = [];
for (const [key, value] of Object.entries(treeStruct)) {
  let leafChildren = [];
  let treeBranch = {id: count, label: key, checked: false, expanded: true,indeterminate: false, children: leafChildren };
  count++;
  for (let itemKey in value) {
    let leaf = {id: count, label: itemKey, checked: false,indeterminate: false };
    leafChildren.push(leaf);
    count++;
  }
  treeContent.push(treeBranch);

}
console.log("目录树内容：",treeContent);

const treeData = ref<TreeNode[]>(treeContent);



const handleToggle = (node: TreeNode) => {
  node.expanded = !node.expanded;
};

const handleCheck = (node: TreeNode) => {
  updateParentState(treeData.value, node);

  // 调用传递的函数来更新

  // TODO：代码合并，参考updateParentState
  if(node.checked){
    console.log(`选中：${node.label}`);
    
    // 处理加载图层
    handleParentChecked(node);



  }
  else{
    console.log(`取消选中：${node.label}`);
    
    // 删除图层
    handleParentCancelChecked(node);

  }
};

const updateParentState = (nodes: TreeNode[], targetNode: TreeNode) => {
  nodes.forEach(node => {
    if (node.children) {
      node.checked = node.children.every(child => child.checked);
      node.indeterminate = !node.checked && node.children.some(child => child.checked || child.indeterminate);
      updateParentState(node.children, targetNode);
    }
  });
};

function handleParentChecked(node: TreeNode){

  // 如果是父节点
  if(node.children){
    node.children.forEach(child => {
      handleParentChecked(child);
    });

  }
  else{
    emit(AddGraphicLayer,node.label);
  }
}
function handleParentCancelChecked(node: TreeNode){

  // 如果是父节点
  if(node.children){
    node.children.forEach(child => {
      handleParentCancelChecked(child);
    });

  }
  else{
    emit(RemoveGraphicLayer,node.label);
  }
}


</script>
